package com.dtda.edu.miaosha.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.dtda.edu.miaosha.bo.OrderBo;
import com.dtda.edu.miaosha.bo.UserInfoBo;
import com.dtda.edu.miaosha.common.exception.BaseExcpController;
import com.dtda.edu.miaosha.common.exception.BusinessException;
import com.dtda.edu.miaosha.common.response.EmBusinessError;
import com.dtda.edu.miaosha.common.response.ResponseType;
import com.dtda.edu.miaosha.service.OrderService;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;


/**
 * @author 袁强
 * @version 2019年2月27日 下午4:38:38
 * 类说明  
 */
@RestController
@RequestMapping("/")
public class OrderController extends BaseExcpController{

	@Autowired
	private OrderService orderService;
	
	@RequestMapping("/createOrder")
	@ResponseBody
	public ResponseType createOrder(HttpServletRequest request, 
			                  @RequestParam(name="itemId")Integer itemId, 
			                  @RequestParam(name="marketId",required=false)Integer marketId,   //非必传字段
			                  @RequestParam(name="itemAmount")Integer itemAmount) throws BusinessException{
		
		
		String is_login = (String)request.getSession().getAttribute("IS_LOGIN");
		if(!("true".equals(is_login))) {
			throw new BusinessException(EmBusinessError.USER_NOT_LOGIN); 
		}
		//获取用户登录信息
		UserInfoBo userInfoBo=(UserInfoBo)request.getSession().getAttribute("LOGIN_USER");
		Integer userId = userInfoBo.getId();
		OrderBo orderBo = orderService.createOrder(userId, marketId, itemId, itemAmount);	
		
		return ResponseType.create(orderBo);
	}
	@RequestMapping("/toMyOrder")
	@ResponseBody
	public ModelAndView toMyOrder(HttpServletRequest request) throws BusinessException{
		UserInfoBo userInfoBo=(UserInfoBo)request.getSession().getAttribute("LOGIN_USER");
		Integer userId = userInfoBo.getId();
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("userId",userId);
		modelAndView.setViewName("/order/myOrder");
		return modelAndView;
	}
	@RequestMapping("/selMyOrder")
	@ResponseBody
	public ResponseType selMyOrder(@RequestBody Object userId)throws Exception{
		String id = (String) userId;
		List<OrderBo> orderBos = orderService.selectOrderByUserId(Integer.valueOf(id));
		if(orderBos.size()== 0) {
			return ResponseType.create("fail", "您当前还没有购买商品！");
		}
		return ResponseType.create(orderBos);
	}
}
